package com.pro.common.modules.service.dependencies.upload.test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class MinioSimpleClient {

    public static void uploadFile(String endpoint, String bucketName, String objectName, String accessKey, String secretKey, File file) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String date = new java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'").format(new java.util.Date());
        String region = "us-east-1"; // MinIO 默认区域
        String service = "s3";

        // Generate the signing key
        String signingKey = getSigningKey(secretKey, date, region, service);

        String urlStr = endpoint + "/" + bucketName + "/" + objectName;
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setRequestProperty("x-amz-date", date); 
        connection.setRequestProperty("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKey + "/" + date + "/" + region + "/" + service + "/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=" + signingKey);
        connection.setRequestProperty("Content-Length", String.valueOf(file.length()));

        // Upload file
        try (OutputStream os = connection.getOutputStream(); FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        }

        // Get the response code
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("Upload failed, response code: " + responseCode);
        }
    }

    private static String getSigningKey(String secretKey, String date, String region, String service) throws NoSuchAlgorithmException, InvalidKeyException {
        byte[] kDate = hmacSha256(("AWS4" + secretKey).getBytes(StandardCharsets.UTF_8), date);
        byte[] kRegion = hmacSha256(kDate, region);
        byte[] kService = hmacSha256(kRegion, service);
        return new String(hmacSha256(kService, "aws4_request"), StandardCharsets.UTF_8);
    }

    private static byte[] hmacSha256(byte[] key, String value) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String minioEndpoint = "http://127.0.0.1:9000";
        String bucketName = "baoyi";
        String objectName = "1_upload.png";
        String accessKey = "minioadmin";
        String secretKey = "minioadmin";
        File file = new File("C:/1.png");

        uploadFile(minioEndpoint, bucketName, objectName, accessKey, secretKey, file);
        System.out.println("File uploaded successfully");
    }
}
